﻿using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace WebSite.ViewModels.Fields
{
    public class DropDownListField : FieldBase
    {
        private readonly List<SelectListItem> m_Items;

        public DropDownListField(string caption, string name, bool isOneRow = false)
            : base(caption, name, null, isOneRow)
        {
            m_Items = new List<SelectListItem>();
        }

        public override IHtmlString Render(HtmlHelper htmlHelper)
        {
            return htmlHelper.DropDownList(Name, m_Items);
        }

        public DropDownListField AddEmpty(bool selected = true, string text = "")
        {
            if (selected)
            {
                Value = null;
            }
            return Add(text, null, selected);
        }

        public DropDownListField Add(string text, object value, bool selected)
        {
            m_Items.Add(new SelectListItem
                            {
                                Text = text,
                                Selected = selected,
                                Value = value == null ? null : value.ToString()
                            });
            if (selected)
            {
                Value = value;
            }
            return this;
        }
    }
}